<template>
    <nly-content-wrapper style="overflow-x:hidden;">
        <nly-content-header>
            <nly-row class="col-12">
                <nly-row class="col-12 ">
                    <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline" style="justify-content: left;">
                    </nly-col>
                    <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
                        <nly-button-group>
                            <nly-button variant="info" @click="PageList" button-class="mr-2">查询</nly-button>
                            <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
                            <nly-button @click="showFunction" variant="info" button-class="mr-2">
                                <nly-icon :icon="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />
                                {{show ? "折叠" : "展开"}}
                            </nly-button>
                        </nly-button-group>
                    </nly-col>
                </nly-row>

                <nly-row class="ml-1 mb-2 lr mt-4" v-show="show">
                    <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;">
                        <form-input name="areaName" title="地区名称" id="name" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.areaName"></form-input>
                    </nly-col>
                </nly-row>
            </nly-row>
            <nly-container fluid></nly-container>
        </nly-content-header>
        <div class="tabpanel_tab_spacer"></div>
        <nly-button-group style="margin-left: 30px;margin-bottom: 10px;display:initial">
            <a-button type="primary" class="crm-btn" @click="AddArea" button-class="mr-2">添加地区</a-button>
            <a-button type="primary" class="crm-btn" @click="importArea" button-class="mr-2">导入地区</a-button>
        </nly-button-group>
        <nly-content>
            <!-- 列表 -->
            <a-table :columns="columns" @change="onTableChange" :data-source="data" bordered :pagination="pagination" :scroll="{ x: 1000, y: 500}" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}" @expand="onTableExpand" table-layout="fixed">
                <template slot="treeSort" slot-scope="text, record">
                    <editable-cell :text="text" @editableChange="onCellChange(record,'treeSort',$event)" :reg="numberReg" />
                </template>
            </a-table>
            <!-- modal 弹窗  -->
            <a-modal v-model="editModal" centered :title="editItem.id ? '编辑地区' : '新增地区'" width="900px" @cancel="hideModal">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 24 }" @submit="saveArea">
                        <div class="line" style="color:#1980Ff;font-size:15px;">基本信息</div>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="上级地区">
                                    <a-input-search :value="parentName" v-model="parentName" placeholder="请选择上级地区" @click="selectArea" @search="selectArea" :read-only="readonly" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="地区名称">
                                    <a-input v-decorator="['areaName', { rules: [{ required: true, message: '地区名称不能为空' }] }]" placeholder="请输入地区名称" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="地区代码">
                                    <a-input v-decorator="['areaCode', { rules: [{ required: true, message: '地区代码不能为空' }] }]" placeholder="请输入地区代码" :disabled="isDisabled" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="地区类型">
                                    <a-radio-group v-model="areaType">
                                        <a-radio :value="1">省份直辖市</a-radio>
                                        <a-radio :value="2">地市</a-radio>
                                        <a-radio :value="3">区县</a-radio>
                                    </a-radio-group>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <!-- <a-col :span="10">
                <a-form-item label="排序号">
                  <a-input
                    v-decorator="['treeSort', { rules: [{ required: false, message: '排序号不能为空' }] }]"
                    placeholder="请输入排序号"
                  />
                </a-form-item>
              </a-col> -->
                            <a-col :span="10">
                                <a-form-item label="拼音码">
                                    <a-input v-decorator="['pym', { rules: [{ required: false, message: '拼音码不能为空' }] }]" placeholder="请输入地区首字母" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="22" :pull="3" key="11">
                                <a-form-item label="备注信息">
                                    <a-textarea placeholder="请输入备注信息" :rows="5" v-decorator="['remarks', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="saveArea">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                </template>
            </a-modal>
            <a-modal :visible="userModal" lg :footer="null" title="地区选择" size="sm" @cancel="hideOfficeModal">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-input-search style="margin-bottom: 8px" placeholder="地区名称" @change="onChange" />
                    <div :style="treeAShow">
                        <a-tree :selected-keys="selectedUserKeys" :tree-data="areaTreeData" :show-line="true" :expanded-keys="expandedUserKeys" @expand="expanedChange" @select="onAreaSelect" />
                    </div>
                    <div :style="treeBShow">
                        <a-tree :selected-keys="selectedUserKeys" :tree-data="areaTreeDataB" :show-line="true" @select="onAreaSelect" />
                    </div>
                </div>
                <a-row>
                    <a-col :span="24" :style="{ textAlign: 'right' }">
                        <a-button type="primary" html-type="submit" @click="saveParentId">保存</a-button>
                        <a-button :style="{ marginLeft: '8px' }" @click="hideOfficeModal">关闭</a-button>
                    </a-col>
                </a-row>
            </a-modal>

            <a-modal :visible="importModal" title="地区导入" size="sm" @cancel="hideOfficeModal">
                <div style="height: 400px;overflow-y:scroll;">
                    <!-- <a-input-search style="margin-bottom: 8px" placeholder="地区名称" @change="onImportChange" /> -->
                    <!-- :expanded-keys="expandedUserKeys"
          @expand="expanedChange"-->
                    <a-tree :selected-keys="selectedUserKeys" :tree-data="improtAreaData" :show-line="true" :checkedKeys="checkedKeys" @select="onAreaSelect" @check="onAreaCheck" checkable />
                </div>
                <template slot="footer">
                    <a-row>
                        <a-col :span="24" :style="{ textAlign: 'right' }">
                            <a-button type="primary" html-type="submit" @click="saveImportData">保存</a-button>
                            <a-button :style="{ marginLeft: '8px' }" @click="hideOfficeModal">关闭</a-button>
                        </a-col>
                    </a-row>
                </template>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { FormInput, EditableCell } from "@/components/Form";
import { PageList, saveSysArea, deleteSysArea, saveAreaList, treeList } from "@/api/area";
import * as moduleApi from "@/api/module";
import { constantRouterComponentsKeys } from "@/router/generator-routers";
import { listToMap } from "../../../utils/tool/map";
import { areaPageListToTree, searchInTreeData } from "@/utils/tree";

let keyMap = new Map();
let treeAreaData = [];
let imporAreaData = [];

export default {
    props: {
        dataList: {
            type: Array,
            default: () => []
        }
    },
    components: {
        FormInput,
        EditableCell
    },
    data () {
        const columns = [
            {
                title: "地区名称",
                dataIndex: "areaName",
                align: "left",
                width: 200,
                customRender: (text, row, index) => {
                    return (<span title={row.treeNames}>{text}</span>);
                }
            },
            {
                title: "地区拼音码",
                dataIndex: "pym"
            },
            {
                title: "地区代码",
                dataIndex: "areaCode"
            },
            {
                title: "地区类型",
                dataIndex: "areaType",
                customRender: (text, row, index) => {
                    const areaType = ["", "省份直辖市", "地市", "区县"];
                    return areaType[text];
                }
            },
            {
                title: "备注",
                dataIndex: "remarks",
            },
            // {
            //   title: "排序号",
            //   dataIndex: "treeSort",
            // },
            {
                title: "状态",
                dataIndex: "status",
                customRender: (text, row, index) => {
                    return text == 2 ? (
                        <nly-badge bg-variant="danger">停用</nly-badge>
                    ) : (
                        <nly-badge bg-variant="success">正常</nly-badge>
                    );
                }
            },
            {
                title: "更新时间",
                dataIndex: "updateDate",
                width: 150
            },
            {
                title: "操作",
                dataIndex: "o",
                key: "o",
                customRender: (text, row, index) => {
                    return (
                        <div class="row justify-content-md-center">
                            <span class="col"></span>
                            <span class="col-sm-auto col-md-auto col-lg-auto col-xl-auto">
                                <a
                                    href="javascript:;"
                                    title="编辑地区"
                                    class="mr-1 col-1"
                                    onClick={() => this.showModal(row)}
                                >
                                    <i class="fa fa-edit" style="color: #69aa46;"></i>
                                </a>
                                {!row.treeLeaf == 0 ? (
                                    <a
                                        href="javascript:;"
                                        title="删除地区"
                                        class="mr-1 "
                                        onClick={() => this.deleteArea(row)}
                                    >
                                        <i class="fa fa-trash-alt" style="color: #dd5a43;"></i>
                                    </a>
                                ) : null}
                                <a
                                    href="javascript:;"
                                    title="添加下级地区"
                                    class="mr-1 col-1"
                                    onClick={() => this.addChildArea(row)}
                                >
                                    <i class="fa fa-plus-square"></i>
                                </a>
                            </span>
                            <span class="col"></span>
                        </div>
                    );
                }
            }
        ];

        return {
            treeAShow: "display:none",
            treeBShow: "display:block",
            editModal: false,
            haveExpandSet: new Set(),
            dataKeySet: new Set(),
            isSelectArea: false,
            isDisabled: false,
            areaType: 1,
            postData: {
                current: 1,
                size: 20,
                areaName: "",
                parentCode: 0
            },
            validateStatus: "success",
            errorMsg: null,
            officeType: "1",
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            keys: [],
            parentName: "", //上级id
            parentId: [], //上级地区名称
            areaTreeData: [], //上级地区数据
            areaTreeDataB: [], //上级地区数据
            improtAreaData: [], //导入地区数据
            expandedUserKeys: [], //地区 tree默认展开的key
            selectedUserKeys: [], //地区 tree默认选中的key
            halfCheckedKeys: [],
            selectedKeys: [],
            checkedKeys: [],
            checkedDatas: [],
            expandedRowKeys: [], //table展开的key
            columns,
            form: this.$form.createForm(this, { name: "advanced_search" }),
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            show: false, //是否显示弹窗
            editItem: {}, //新增/编辑对象
            TreeSortEditList: new Map(), //菜单排序修改集合
            importModal: false,
            userModal: false,
        };
    },
    mounted () {
        this.PageList();
        this.treeUseData(null);
        this.treeUseData(1);
    },
    computed: {
        parentMenu: function () {
            const map = new Map();
            map.set(this.editItem.parentId, "");
            return map;
        },
        moudelsMap: function () {
            return listToMap(this.moduleList, {
                key: "moduleCode",
                value: "moduleName"
            });
        },
        componentSelectList: function () {
            const dataList = new Array();
            constantRouterComponentsKeys().forEach(item => {
                dataList.push({ key: item, title: item });
            });
            return dataList;
        }
    },
    methods: {
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                "size": value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
            this.PageList();
        },
        //添加
        AddArea () {
            console.log("AddMenu...");
            this.editItem = {};
            this.parentId = [];
            this.selectedUserKeys = [];
            this.parentName = "";
            this.isDisabled = false;
            this.editModal = true;
        },
        //添加子地区
        addChildArea (area) {
            this.parentId = [area.areaCode];
            this.selectedUserKeys = this.parentId;
            this.parentName = area.areaName;
            this.editItem = {};
            this.editModal = true;
        },
        //删除地区
        deleteArea (area) {
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该地区吗？',
                onOk () {
                    deleteSysArea({ id: area.id, parentCode: area.parentCode })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                _this.isSelectArea = true;
                                //刷新 列表
                                _this.PageList();
                            }
                        })
                },
                onCancel () {
                },
            });
        },
        //获取地区列表
        PageList () {
            this.data = [];
            const { postData } = this;
            PageList(postData)
                .then(response => {
                    console.log("获取地区列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        const childrenNav = [];
                        Object.assign(this.pagination, {
                            total
                        });
                        areaPageListToTree(records, childrenNav, 0);
                        this.data = childrenNav;
                        this.haveExpandSet.clear();
                        this.dataKeySet.clear();
                        this.dataKeySet = new Set(records.map(f => f.areaCode));
                        console.log("childrenNav", childrenNav);
                    }
                })
                .catch(error => { });
        },
        //查询table 子集数据
        onTableExpand (expanded, record) {
            if (!expanded || this.haveExpandSet.has(record.areaCode)) return false;
            const postData = {
                current: 1,
                size: 1000,
                parentCode: record.areaCode
            };
            PageList(postData)
                .then(response => {
                    console.log(`获取：${record.dictLabel}——的子集`, response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records } = data;
                        records.forEach(item => {
                            if (!this.dataKeySet.has(item.areaCode)) {
                                if (!item.treeLeaf) {
                                    item.children = [];
                                }
                                item.key = item.areaCode;
                                record.children.push(item);
                                this.dataList.push(item);
                                this.dataKeySet.add(item.areaCode);
                            }
                        });
                        this.data = [...this.data];
                        this.haveExpandSet.add(record.areaCode);
                    }
                })
                .catch(error => { });
        },
        //选择上级地区
        selectArea () {
            this.userModal = true;
            this.treeAShow = "display:none";
            this.treeBShow = "display:block";

            if (this.isSelectArea) {
                keyMap = new Map();
                this.treeUseData(null);
            } else {
                this.areaTreeData = treeAreaData;
                this.expandedUserKeys = [];
            }
        },
        //渲染tree数据
        treeUseData (companyId) {
            const postData = {
                companyId: companyId
            };
            treeList(postData)
                .then(response => {
                    console.log("获取地区列表", response);
                    console.log("postDat========", postData);
                    if (response.code === 200) {
                        const { data } = response;
                        const records = data;
                        const childrenNav = [];
                        if (companyId != 1) {
                            this.keys = [];
                            this.halfCheckedKeys = [];
                        }
                        for (let i = 0; i < records.length; i++) {
                            const node = records[i];
                            const code = node.areaCode;
                            const title = node.areaName;
                            this.dataList.push({ code, title });
                            if (companyId != null) {
                                // if (node.treeLeaf == 1) {
                                //   this.keys.push(code);
                                // } else {
                                //   this.halfCheckedKeys.push(code);
                                // }
                            } else {
                                keyMap.set(code, node);
                            }
                        }
                        console.log("postDat========", keyMap);
                        this.checkedKeys = this.keys;
                        areaPageListToTree(records, childrenNav, 0);
                        if (!companyId == 1) {
                            this.areaTreeData = childrenNav;
                            treeAreaData = childrenNav;
                            this.areaTreeDataB = treeAreaData;
                        } else {
                            this.improtAreaData = childrenNav;
                            imporAreaData = childrenNav;
                        }
                        console.log("parentId", childrenNav);
                        //this.expandedUserKeys = keys;
                        this.selectedUserKeys = this.parentId;
                        this.isSelectArea = false;
                    }
                })
                .catch(error => { });
        },
        //地区保存
        saveArea (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => {
                if (!err) {
                    let id = this.editItem.id;
                    this.editItem = { ...values };
                    this.editItem.id = id;
                    this.editItem.areaType = this.areaType;
                    if (this.parentId[0]) {
                        console.log(keyMap);
                        this.editItem.parentCode = this.parentId[0];
                        this.editItem.parentCodes = keyMap.get(this.parentId[0]).parentCodes;
                        this.editItem.treeNames = keyMap.get(this.parentId[0]).treeNames;
                    }
                    console.log(this.editItem);
                    saveSysArea(this.editItem)
                        .then(response => {
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //this.isSelectArea = true;
                                keyMap = new Map();
                                this.treeUseData(null);
                                //刷新 列表
                                this.PageList();
                                this.hideModal();
                            }
                        })

                }
            });
        },
        showFunction () {
            this.show = !this.show;
        },
        selection (keys) {
            this.selectedKeys = keys;
            console.log("rowKeys", this.selectedKeys);
        },
        expanedChange (keys) {
            console.log(keys);
            this.expandedUserKeys = keys;
        },
        //编辑地区
        showModal (editItem) {
            console.log("editItem", editItem);
            this.editItem = { ...editItem };
            this.parentId = [this.editItem.parentCode];
            this.isDisabled = true;
            if (this.editItem.parentCode == 0) {
                this.parentName = "";
            } else {
                console.log("keyMap", keyMap);
                this.parentName = keyMap.get(this.editItem.parentCode).areaName;
            }
            this.areaType = parseInt(this.editItem.areaType);
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        parentName: this.$form.createFormField({
                            value: this.parentName
                        }),
                        areaName: this.$form.createFormField({
                            value: this.editItem.areaName
                        }),
                        areaCode: this.$form.createFormField({
                            value: this.editItem.areaCode
                        }),
                        treeSort: this.$form.createFormField({
                            value: this.editItem.treeSort
                        }),
                        pym: this.$form.createFormField({
                            value: this.editItem.pym
                        }),
                        remarks: this.$form.createFormField({
                            value: this.editItem.remarks
                        })
                    };
                }
            });
            this.editModal = true;
        },
        hideModal () {
            this.editModal = false;
        },
        hideOfficeModal () {
            this.userModal = false;
            this.importModal = false;
        },
        //保存地区父级id
        saveParentId () {
            this.userModal = false;
            this.parentId = this.selectedUserKeys;
            this.parentName = keyMap.get(this.parentId[0]).areaName;
            if (this.parentName != null) {
                this.validateStatus = "success";
                this.errorMsg = null;
            }
        },
        //保存导入地区
        saveImportData () {
            console.log("保存导入地区", this.checkedKeys);
            if (this.checkedKeys.length > 0) {
                saveAreaList({
                    areaCodes: this.checkedKeys.concat(this.halfCheckedKeys)
                }).then(response => {
                    if (response.code == 200) {
                        this.$message.success("保存成功");
                        this.PageList();
                        this.isSelectArea = true;
                        // this.$refs["import-modal"].hide();
                        this.importModal = false;
                    }
                });
            } else {
                this.$message.warn("请选择地区");
            }
        },
        onTableChange (pagination, filters, sorter) {
            console.log("================", pagination);
            Object.assign(this.postData, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        onCellChange (item, dataIndex, editValue) {
            if (item[dataIndex] != editValue) {
                const edit = { id: item.id, [dataIndex]: editValue };
                this.TreeSortEditList.set(item.id, edit);
            } else {
                this.TreeSortEditList.delete(item.id);
            }
            console.log([...this.TreeSortEditList.values()]);
        },
        //查询条件重置
        reset () {
            this.postData = {
                "current": 1,
                "size": 20,
                areaName: "",
                parentCode: 0
            };
        },
        //表单重置
        handleReset () {
            this.form.resetFields();
        },
        //选择地区
        onAreaSelect (key, info) {
            console.log("onSelect", key, info);
            this.selectedUserKeys = key;
        },
        //多选地区
        onAreaCheck (keys, info) {
            console.log(keys, info.halfCheckedKeys);
            //this.checkedDatas = info.checkedNodes;
            this.checkedKeys = keys;
            this.halfCheckedKeys = info.halfCheckedKeys;
        },
        //导入地区
        importArea () {
            //this.treeUseData(null);
            // this.$refs["import-modal"].show();
            this.importModal = true;
        },
        //tree 搜索
        onChange (e) {
            const value = e.target.value;
            console.log(value);
            if (value) {
                this.treeAShow = "display:block";
                this.treeBShow = "display:none";
                const keys = [];
                const treeData = searchInTreeData(keys, treeAreaData, "title", value);
                this.areaTreeData = treeData;
                this.expandedUserKeys = keys;
            } else {
                this.treeAShow = "display:none";
                this.treeBShow = "display:block";
                //this.areaTreeData = treeAreaData;
                this.expandedUserKeys = [];
            }
        },
        //tree 搜索
        onImportChange (e) {
            const value = e.target.value;
            console.log(value);
            if (value) {
                const keys = [];
                const treeData = searchInTreeData(keys, imporAreaData, "title", value);
                this.improtAreaData = treeData;
                //this.expandedUserKeys = keys;
            } else {
                this.improtAreaData = imporAreaData;
            }
        }
    },
    watch: {}
};
</script>
<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
    /* .crm-btn {
                          margin-left: 10px;
                          margin-bottom: 10px;
                        } */
</style>
